package ru.st.selenium.pages;

import static org.openqa.selenium.support.ui.ExpectedConditions.*;

import java.util.List;
import java.util.ArrayList;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

public class InternalPage extends AnyPage {

	public InternalPage(PageManager pages) {
		super(pages);
	}

	public InternalPage ensurePageLoaded() {
		super.ensurePageLoaded();
		wait.until(presenceOfElementLocated(By.cssSelector("nav")));
		return this;
	}

	@FindBy(css = "nav a[href $= '?go=profile']")
	private WebElement userProfileLink;

	@FindBy(css = "nav a[href $= '?go=users']")
	private WebElement userManagementLink;

	@FindBy(css = "nav a[href $= '?logout']")
	private WebElement logoutLink;

	public UserProfilePage clickUserProfilePage() {
		userProfileLink.click();
		return pages.userProfilePage;
	}

	@FindBy(xpath = "//input[ @id = \"q\" ][ @class = \"inputDefault\"] ")
	WebElement searchInput;

	@FindBy(xpath = "//div[@id=\"results\"]/a")
	List<WebElement> films;

	@FindBy(css = ".title")
	List<WebElement> titleFilms;

	public void printList() {
		System.out.println("Found Movies " + films.size());
		for (WebElement film : films) {
			System.out.println(film.getText());
		}
	}

	public boolean findFilmByTitle(String mode) {
		String title;
		if (mode == "expected") {
			title = pickUpFilmTitleRandom();
		} else {
			title = "EskjanmjhGfrTdseRTYUiolkZcBGRedWQopIUkJYtgFBHoHDliKa";
		}
		for (WebElement film : films) {
			List<WebElement> titles = film.findElements(By
				.xpath(".//div[ @class=\"title\" ]"));
			if (titles.size() > 0 && titles.get(0).getText().matches(title)) {
				System.out.println("Found Movie! " + titles.get(0).getText());
				film.click();
				return true;
			}
		}
		return false;
	}

	public String pickUpFilmTitleRandom() {
		List<String> stringList = new ArrayList<String>();
		for (WebElement film : titleFilms) {
			stringList.add(film.getText());
		}
		int size = stringList.size();
		return stringList.get(random(size));
	}

	private int random(int n) {
		int i = (int) (Math.random() * (n + 1));
		return i;
	}

	public boolean isOnThisPage() {
		return searchInput.isDisplayed();
	}

	public UserManagementPage clickUserManagementLink() {
		userManagementLink.click();
		return pages.userManagementPage;
	}

	public LoginPage clickLogoutLink() {
		logoutLink.click();
		wait.until(alertIsPresent()).accept();
		return pages.loginPage;
	}
}
